package com.gdk.ksoft.ui.works;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.data.entry.tables.CustomerLatLngTable;
import com.gdk.ksoft.data.entry.tables.DeliverGoodsTable;
import com.gdk.ksoft.ui.works.adapters.FworkCustomerAdapter;
import com.gdk.ksoft.ui.works.models.FworkCustomerModel;
import com.gdk.ksoft.assembly.dbhelper.FworkDbHelper;
import com.gdk.ksoft.assembly.dialog.LocationRecorderDialog;
import com.gdk.ksoft.assembly.utils.extensions.ControlUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemClick;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by hel on 2014-11-21.
 * 工作页面
 */
public class FragmentWork extends Fragment {

    public static final String TAG = FragmentWork.class.getSimpleName();

    @ViewInject(R.id.fwork_lstCustomer)private ListView lstCustomer;//任务列表
    @ViewInject(R.id.fwork_etSearch)private EditText etSearch;//搜索输入框
    private List<FworkCustomerModel> customerlst = new ArrayList<FworkCustomerModel>();//客户数据列表
    private List<FworkCustomerModel> pageCustomerlst = new ArrayList<FworkCustomerModel>();//客户数据列表
    private FworkCustomerAdapter customerAdapter;//客户数据填充器
    private ProgressDialog progressDialog;//进度提示框
    private boolean isCloseByCustomer = true;//是否是查询附近的客户
    private DbUtils dbUtils;//数据库操作对象
    private int currentPageIndex = 0;//当前页码
    private int pageCount = 0;//当前总页数
    private static final int PAGE_COUNT = 20;//最大每页加载20个

    public static final int MSG_REFRESH_CUSTOMERS = 0x00001;//刷新列表数据
    public static final int MSG_QUERY_ERROR = 0x00002;//查询出错
    public static final int MSG_QUERY_DONE = 0x0003;//查询完成

    public Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case MSG_REFRESH_CUSTOMERS:
                    dealCustomerInfo(msg);//处理客列表户数据
                    break;
                case MSG_QUERY_ERROR:
                    Toast.makeText(getActivity(),"查询出错了 (⊙o⊙)…",Toast.LENGTH_SHORT).show();
                    break;
                case MSG_QUERY_DONE://查询完成
                    if(progressDialog!=null && progressDialog.isShowing())
                        progressDialog.dismiss();//隐藏进度提示框
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 创建视图页面
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_work,null);
        ViewUtils.inject(this, rootView);
        return rootView;
    }

    /**
     * 页面创建后初始化数据
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dbUtils = SQLiteUtils.getInstance(getActivity()).getDbUtils();
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("正在查询中,请稍后...");
        customerAdapter = new FworkCustomerAdapter(getActivity(),pageCustomerlst);
        lstCustomer.setAdapter(customerAdapter);
        lstCustomer.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                int lastItem = view.getLastVisiblePosition();
                if(scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && lastItem == lstCustomer.getCount()-1){
                    currentPageIndex++;
                    if(currentPageIndex > pageCount-1){
                        currentPageIndex = pageCount -1;
                        return;
                    }
                    List<FworkCustomerModel> list = null;
                    int backPageIndex = currentPageIndex+1;//前一页的索引
                    if(currentPageIndex == pageCount-1){//已经是最后一页
                        int dataLen = customerlst.size();
                        list = customerlst.subList(currentPageIndex*PAGE_COUNT,
                                dataLen%PAGE_COUNT==0?backPageIndex*PAGE_COUNT
                                        :currentPageIndex*PAGE_COUNT+dataLen%PAGE_COUNT);
                    }else{
                        list = customerlst.subList(currentPageIndex*PAGE_COUNT,backPageIndex*PAGE_COUNT);
                    }
                    pageCustomerlst.addAll(list);
                    customerAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        queryNeighborhoodCustomers();//查询附近的客户
    }

    /**
     * 列表项点击事件
     * @param av
     * @param view
     * @param position
     * @param itemId
     */
    @OnItemClick(value={R.id.fwork_lstCustomer})
    public void onItemClick(AdapterView<?> av,View view,int position,long itemId){
        final FworkCustomerModel item = customerlst.get(position);
        if(TextUtils.isEmpty(item.latLng)){
            final LocationRecorderDialog dialog = new LocationRecorderDialog(getActivity(),item.customerName,item.receiverAddress);
            dialog.setOnPositiveNegitiveClick(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(dialog!=null && dialog.isShowing()) {//处理对话框
                        dialog.dismiss();
                    }
                    switch(v.getId()){
                        case R.id.drecorder_location_txtCustomerCancel://取消
                            break;
                        case R.id.drecorder_location_txtCustomerOK://确定
                            try {
                                item.latLng = SystemData.currentLocation.getLatitude()+","+SystemData.currentLocation.getLongitude();
                                customerAdapter.notifyDataSetChanged();
                                DeliverGoodsTable data = new DeliverGoodsTable();
                                data.did =item.localeAddressId;
                                data.jwd = item.latLng;//获取经纬度
                                DbUtils dbUtils = SQLiteUtils.getInstance(getActivity()).getDbUtils();
                                dbUtils.update(data, "jwd");
                                CustomerLatLngTable clatlng = new CustomerLatLngTable();
                                clatlng.kh_id = item.netCustomerId;
                                clatlng.shdz_id = item.netAddressId;
                                clatlng.latlng = data.jwd;
                                clatlng.djbz = 0;//表示单机
                                dbUtils.save(clatlng);//存储经纬度到新表
                            }catch(Exception e){
                                Toast.makeText(getActivity(),"更新经纬度数据失败!",Toast.LENGTH_SHORT).show();
                                e.printStackTrace();
                            }
                            break;
                    }
                    gotoCustomerDetailActivity(item);
                }
            });
            dialog.show();
        }else{
            gotoCustomerDetailActivity(item);
        }
    }

    /**
     * 跳转到客户下单页面
     * @param item
     */
    public void gotoCustomerDetailActivity(FworkCustomerModel item){
        //页面跳转
        Intent intent = new Intent(getActivity(),CustomerDetailActivity.class);
        intent.putExtra("netCustomerId",item.netCustomerId);
        intent.putExtra("customerName",item.customerName);
        intent.putExtra("customerContactor",item.contactorName+" "+item.contactorPhone);
        intent.putExtra("receiverContactor",item.receiverName+" "+item.receiverPhone);
        intent.putExtra("receiverAddress",item.receiverAddress);
        intent.putExtra("netAddressId",item.netAddressId);//传递送货地址网络ID
        intent.putExtra("localeAddreesId",item.localeAddressId);//传递送货地址本地ID
        intent.putExtra("customerType",item.customerType);//传递客户地图图标
        intent.putExtra("latlng",item.latLng);//传递经纬度数据
        intent.putExtra("priceName",item.priceName);//客户的价格名称
        startActivity(intent);
//        startActivityForResult(intent, 0x0001);
        getActivity().overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
    }

    /**
     * 视图控件点击事件
     * @param view
     */
    @OnClick(value={R.id.fwork_txtSearch,R.id.fwork_imgFindNeighborhoodCustomer})
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.fwork_txtSearch://搜索操作
                executeFindCustomerByKeyword();//通过关键字查询客户信息
                break;
            case R.id.fwork_imgFindNeighborhoodCustomer://附近客户
                etSearch.setText("");//清空查询关键字
                queryNeighborhoodCustomers();//查询附近的客户
                break;
            default:
                break;
        }
    }

    /**
     * 通过关键字查询客户信息
     */
    public void executeFindCustomerByKeyword(){
        final String keyword = etSearch.getText().toString();
        if(TextUtils.isEmpty(keyword)){
            ControlUtils.showToast(getActivity(),"搜索关键字不能为空!", Gravity.CENTER,Toast.LENGTH_SHORT);
            return;
        }
        queryCustomerByKeyword(keyword);//通过关键字查询客户
    }

    /**
     * 通过关键字查询客户
     */
    public void queryCustomerByKeyword(final String keyword){
        isCloseByCustomer = false;
        progressDialog.show();//显示进度提示框
        new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    List<FworkCustomerModel> customerlst = FworkDbHelper.queryAllCustomers(dbUtils, keyword);
                    handler.obtainMessage(MSG_REFRESH_CUSTOMERS,customerlst).sendToTarget();
                }catch(Exception e){
                    handler.sendEmptyMessage(MSG_QUERY_ERROR);
                    e.printStackTrace();
                    System.out.println("-----> 搜索客户发送异常："+e.getMessage());
                }finally {
                    handler.sendEmptyMessage(MSG_QUERY_DONE);
                }
            }
        }).start();
    }


    /**
     * 查询附近的客户
     */
    public void queryNeighborhoodCustomers(){
        isCloseByCustomer = true;
        progressDialog.show();//显示进度提示框
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    List<FworkCustomerModel> customerlst = FworkDbHelper.findNeighborhoodCustomers(dbUtils);
                    Collections.sort(customerlst,new Comparator<FworkCustomerModel>() {
                        @Override
                        public int compare(FworkCustomerModel lhs, FworkCustomerModel rhs) {
                            try{
                                LatLng curLatlng = new LatLng(SystemData.currentLocation.getLatitude(),SystemData.currentLocation.getLongitude());
                                String[] latlngString1 = lhs.latLng.split(",");
                                String[] latlngString2 = rhs.latLng.split(",");
                                LatLng latLng1 = new LatLng(Double.parseDouble(latlngString1[0]),Double.parseDouble(latlngString1[1]));
                                LatLng latLng2 = new LatLng(Double.parseDouble(latlngString2[0]),Double.parseDouble(latlngString2[1]));
                                double distance1 = DistanceUtil.getDistance(curLatlng,latLng1),
                                        distance2 = DistanceUtil.getDistance(curLatlng,latLng2);
                                return (int)(distance1-distance2);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                            return 0;
                        }
                    });
                    handler.obtainMessage(MSG_REFRESH_CUSTOMERS,customerlst).sendToTarget();
                }catch (Exception e){
                    handler.sendEmptyMessage(MSG_QUERY_ERROR);
                    e.printStackTrace();
                    System.out.println("-----> 搜索附近客户发送异常：" + e.getMessage());
                }finally{
                    handler.sendEmptyMessage(MSG_QUERY_DONE);
                }
            }
        }).start();
    }

    /**
     * 处理客列表户数据
     * @param msg
     */
    public void dealCustomerInfo(Message msg){
        List<FworkCustomerModel> tmplst = (ArrayList<FworkCustomerModel>)msg.obj;//获取所有的客户数据
        if(tmplst == null || tmplst.size()<=0) {//数据为空时，清理原数据
            currentPageIndex = 0;//当前页面
            pageCount = 0;//页码置为0
            customerlst.clear();//清空临时数据源
            pageCustomerlst.clear();//清空数据源
            customerAdapter.notifyDataSetChanged();//刷新列表
            Toast.makeText(getActivity(),"当前没有数据加载!",Toast.LENGTH_SHORT).show();
            return;
        }
        customerlst.clear();//清空临时数据源
        customerlst.addAll(tmplst);//添加新的数据
        currentPageIndex = 0;//当前页面
        int dataLen = customerlst.size();//数据长度
        pageCount = dataLen%PAGE_COUNT==0?dataLen/PAGE_COUNT:dataLen/PAGE_COUNT+1;//获取页码数
        pageCustomerlst.clear();//清空数据源
        customerAdapter.notifyDataSetChanged();
        if(pageCount == 1) pageCustomerlst.addAll(customerlst);//如果只有一页数据
        else pageCustomerlst.addAll(customerlst.subList(0,PAGE_COUNT));
        customerAdapter.notifyDataSetChanged();
        lstCustomer.setSelection(0);//设置滚动到第一项
    }

//
//    @Override
//    public void onResume() {
//        super.onResume();
//        if(isCloseByCustomer){
//            queryNeighborhoodCustomers();//查询附近的客户
//        }else{
//            executeFindCustomerByKeyword();//通过关键字查询客户信息
//        }
//    }
}
